<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Announcement;
use app\common\model\answer\Log;
use app\common\model\Banner;
use app\common\model\Course as ModelCourse;
use app\common\model\course\Category;
use app\common\model\course\Course as CourseCourse;
use app\common\model\course\Qusetion;
use app\common\model\course\Train;
use app\common\model\course\User as CourseUser;
use app\common\model\question\Option;
use app\common\model\Systemconfig;
use app\common\model\User;
use think\Db;
use think\Request;
use think\Validate;

/**
 * 课程接口
 */
class Course extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (课程分类)
     * @ApiMethod (GET)
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function course_category()
    {
        $params = request()->param();
        extract($params);

        $lists = Category::all(['acct_id' => $this->auth->acct_id]);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (课程列表)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="分类ID")
     * @ApiParams (name="type", type="int", required=true, sample="", description="1=线上课程,2=线下课程")
     * @ApiParams (name="subject", type="int", required=true, sample="", description="1=科目一,2=科目二,3=科目三")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function course_list()
    {
        $params = request()->param();
        extract($params);
        if (empty($subject)) {
            $this->error('请选择科目');
        }
        if ($id > 0) {
            $where['category_id'] = $id;
        }
        if (isset($keywords) && $keywords) {
            $where['title'] = ['like', '%' . $keywords . '%'];
        }
        $where['subject'] = $subject;
        $where['type'] = $type;
        $where['acct_id'] = $this->auth->acct_id;
        $lists = CourseCourse::where($where)->paginate();
        foreach ($lists as $k => $v) {
            if ($this->auth->isLogin()) {
                $v->sign_up = CourseUser::get(['c_id' => $v->id, 'user_id' => $this->auth->id]) ? true : false;
                $v->train = Train::get(['c_id' => $v->id, 'user_id' => $this->auth->id]);
                if ($v->train) {
                    $v->check_train = true;
                } else {
                    $v->check_train = false;
                }
            }
            $v->sign_num = CourseUser::where('c_id', $v->id)->count() ?? 0;
            if ($v['total_num'] <= $v->sign_num) {
                $v->check_sign = false;
            } else {
                $v->check_sign = true;
            }
        }
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (课程详情)
     * @ApiMethod (GET)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="分类ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function course_info()
    {
        $params = request()->param();
        extract($params);
        $info = CourseCourse::get($id);
        if ($info) {
            if ($this->auth->isLogin()) {
                $info->sign_up = CourseUser::get(['c_id' => $id, 'user_id' => $this->auth->id]) ? true : false;
            }
            $info->sign_num = CourseUser::where(['c_id' => $id])->count();
        }
        $this->success('', $info);
    }
    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (开始考试)
     * @ApiMethod (POST)
     * @ApiParams (name="subject", type="int", required=true, sample="", description="1=科目一,2=科目二,3=科目三")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function start_exam()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['subject', 'require|in:1,2,3', '请选择考试科目']
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        Db::startTrans();
        try {
            $user = $this->auth->getUser();
            if ($subject == 1 && $user['complete'] == 1) {
                exception('您已完成科目一考试');
            }
            if ($subject == 2) {
                if ($user['complete'] == 0) {
                    exception('请先完成科目一考试');
                }
                if ($user['complete_2'] == 1) {
                    exception('您已完成科目二考试');
                }
            }
            if ($subject == 2 && $user['complete_3'] == 1) {
                if ($user['complete_2'] == 0) {
                    exception('请先完成科目二考试');
                }
                if ($user['complete_3'] == 1) {
                    exception('您已完成科目三考试');
                }
            }
            Log::where('user_id', $this->auth->id)->where('subject', $subject)->where('acct_id', $this->auth->acct_id)->delete();
            Db::commit();
        } catch (\Exception $th) {
            Db::rollback();
            $this->error($th->getMessage());
        }
        $this->success('');
    }

    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (题库)
     * @ApiMethod (GET)
     * @ApiParams (name="subject", type="int", required=true, sample="", description="1=科目一,2=科目二,3=科目三")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function question()
    {
        $params = request()->param();
        extract($params);
        $validate = new Validate([
            ['subject', 'require|in:1,2,3', '请选择考试科目']
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $system = Systemconfig::whereIn('name', ['online_course' . $subject, 'offline_course' . $subject])->where('acct_id', $this->auth->acct_id)->column('id,value');
        list($online_course, $offline_course) = array_values($system);
        //线上课程类题
        $online_course = Qusetion::with(['option'])->where('type', 1)->where('subject', $subject)->where('acct_id', $this->auth->acct_id)->orderRaw('rand()')->limit($online_course)->select();
        //线下课程类题
        $offline_course = Qusetion::with(['option'])->where('type', 2)->where('subject', $subject)->where('acct_id', $this->auth->acct_id)->orderRaw('rand()')->limit($offline_course)->select();
        $lists = array_merge($online_course, $offline_course);
        $this->success('', $lists);
    }
    /**
     * @Author LK
     * @date: 2024-03-26 
     * @ApiTitle (答题)
     * @ApiMethod (POST)
     * @ApiParams (name="q_id", type="integer", required=true, sample="", description="题库ID")
     * @ApiParams (name="answer", type="string", required=true, sample="", description="答案")
     * @ApiParams (name="total_num", type="string", required=true, sample="", description="总数量")
     * @ApiParams (name="subject", type="string", required=true, sample="", description="总数量")
     * @ApiReturnParams (name="code", type="integer", required=true, description="200=答题结束,1=答题成功,0=答题失败")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function answer()
    {
        $params = request()->param();
        extract($params);
        $passing_mark = Systemconfig::where('name', 'passing_mark' . $subject)->where('acct_id', $this->auth->acct_id)->value('value') ?? 95;
        $params['user_id'] = $this->auth->id;
        $params['acct_id'] = $this->auth->acct_id;
        $num = Log::where('user_id', $params['user_id'])->where('subject', $subject)->order('serial desc')->value('serial') ?? 0;
        $params['serial'] = $num + 1;
        $count = Log::where('user_id', $this->auth->id)->where('correct', 1)->where('subject', $subject)->count();

        $mark = bcmul($count / $total_num, 100, 0);

        if ($params['serial'] > $total_num) {
            if ($mark >= $passing_mark) {
                $this->success('考试通过', $mark);
            } else {
                $this->error('考试不通过', $mark, -1);
            }
        }
        $ids = Option::where('q_id', $q_id)->where('correct', 1)->column('id');
        if (!$answer) {
            $this->error('请选择答案');
        }
        $check = array_diff($ids, explode(',', $answer));
        $params['correct'] = $check ? 0 : 1;
        $res = Log::create($params, true);
        if ($res) {
            if ($params['serial'] == $total_num) {
                $count = Log::where('user_id', $this->auth->id)->where('correct', 1)->where('subject', $subject)->count();
                $mark = bcmul($count / $total_num, 100, 0);
                if ($subject == 1) {
                    $data = [
                        'complete' => 1,
                        'mark' => $mark,
                        'finishtime' => time(),
                    ];
                } elseif ($subject == 2) {
                    $data = [
                        'complete_2' => 1,
                        'mark_2' => $mark,
                        'finish2time' => time(),
                    ];
                } else {
                    $data = [
                        'complete_3' => 1,
                        'mark_3' => $mark,
                        'finish3time' => time(),
                    ];
                }
                if ($mark >= $passing_mark) {
                    User::update($data, ['id' => $this->auth->id]);
                    $this->success('考试通过', $mark, 200);
                } else {
                    $this->error('考试不通过', $mark, -1);
                }
            }
            $this->success('成功');
        }
        $this->error('系统错误');
    }
    /**
     * @Author LK
     * @date: 2024-04-08 
     * @ApiTitle (报名课程)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="课程id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function res_course()
    {
        $params = request()->param();
        extract($params);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $course = ModelCourse::get($id);
        if (!$course) {
            $this->error('课程不存在');
        }
        if ($course['endtime'] < time()) {
            $this->error('课程报名时间已结束');
        }
        if ($course['total_num'] <= CourseUser::where('c_id', $id)->count()) {
            $this->error('报名人数已满');
        }
        $info = CourseUser::get(['c_id' => $id, 'user_id' => $uid, 'acct_id' =>  $this->auth->acct_id]);
        if ($info) {
            $this->error('已报名');
        }
        $res = CourseUser::create([
            'c_id' => $id,
            'user_id' => $uid,
            'acct_id' => $this->auth->acct_id
        ]);
        if ($res) {
            $this->success('报名成功');
        }
        $this->error('报名失败');
    }
    /**
     * @Author LK
     * @date: 2024-04-09 
     * @ApiTitle (取消报名)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */

    public function cancel_sign()
    {
        $params = request()->param();
        extract($params);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $info = CourseUser::get(['c_id' => $id, 'user_id' => $uid, 'acct_id' =>  $this->auth->acct_id]);
        if (!$info) {
            $this->error('未报名');
        }
        $res = $info->delete();
        if ($res) {
            $this->success('取消成功');
        }
        $this->error('取消失败');
    }

    /**
     * @Author LK
     * @date: 2024-04-08 
     * @ApiTitle (课程培训)
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, sample="", description="课程id")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':1,'msg':'返回成功'})
     */
    public function course_train()
    {
        $params = request()->param();
        extract($params);
        if (!isset($id) || !$id) {
            $this->error('参数错误');
        }
        $uid = $this->auth->id;
        $info = Train::get(['c_id' => $id, 'user_id' => $uid, 'acct_id' =>  $this->auth->acct_id]);
        if (!$info) {
            Train::create([
                'c_id' => $id,
                'user_id' => $uid,
            ]);
        }
        $this->success('');
    }
}
